
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        self.setDefaultBehaviour(self.MainBehav())
        self.info=[{"tipo":"Italiano","Calle":"lacalle2222"}]

    class MainBehav(Behaviour.OneShotBehaviour):


        def _process(self):
                print "Agent "+agent+" registering"
                time.sleep(10)
                lista= b.getOrganizationList()
                for i in lista:
                    info=b.getOrganizationInfo(i)
                    if info.has_key("goal"):
                        goal=info["goal"]
                        g=eval(goal)
                        if g.has_key("necesita") and "fuentes de informacion" in g["necesita"]:
                            o=MyOrganization(b,nick="fuenteB", name=i)
                            b.joinOrganization(o)
                            l=o.getUnitList()
                            for u in l:
                                info=o.getUnitInfo(u)
                                if info["type"]=="Hierarchy" and "fuentes de informacion" in eval(info["goal"])["necesita"]:
                                    m=MyUnit(b, nick="fuenteB", password="pass",name=u)
                                    try:
                                        o.joinUnit(m)
                                    except Unit.MembersOnly:
                                        print "Excepcion:MembersOnly"
                                        d={"ofrece":"fuentes de informacion"}
                                        entry=o.requestEntryUnit(u,d)
                                        print entry
                                        if entry:
                                                m=MyUnit(b, nick="fuenteB", password=entry,name=u)
                                                o.joinUnit(m)
                                                print m.getGoal()
                                                print "Buscando mensaje"
                                                mens=m.receiveMessage()
                                                while not mens:
                                                    mens=m.receiveMessage()
                                                content=[]
                                                for i in self.myAgent.info:
                                                    if i["tipo"]==mens.getContent():
                                                        content.append(i)
                                                if content!=[]:
                                                    ans=ACLMessage.ACLMessage()
                                                    ans.setPerformative("inform")
                                                    ans.setSender(self.myAgent.getAID())
                                                    ans.addReceiver(mens.getSender())
                                                    ans.setContent(str(content))
                                                    m.sendPrivateMessage(ans,mens.getSender().getName())

class MyOrganization(Federation.Federation):
    def _process(self):
        #u=MyUnit(agent=self.myAgent, nick="gestor", name="supervision")
        #self.addUnit(u)
        time.sleep(2000)



class MyUnit(Unit.Hierarchy):
    def _process(self):
        time.sleep(300)
        """
        mens=ACLMessage.ACLMessage()
        mens.setPerformative("request")
        mens.setSender(self.myAgent.getAID())
        aid=AID.aid("pepe@perez",["xmpp://pepe@perez"])
        mens.addReceiver(aid)
        mens.setContent("Trabajo??")
        time.sleep(20)
        print "Solicitamos"+str(mens)
        m=self.getMemberList()
        print m
        for i in m:
            self.sendPrivateMessage(i,mens)
            #self.sendMessage(mens)
        print self.receiveMessage()
        time.sleep(100)
        for i in m:
            self.kickAgent(i)
        """

    def creationPermissionTest(self,sender,desc=None):
       return False
    def entryUnitTest(self,sender,desc=None):
      d=desc
      if d.has_key("ofrece"):
           if str(d["ofrece"])=="fuentes de informacion":
               return True
      return False
    def askMembers(self,about):
        members=self.getMemberList()
        for m in members:
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("request")
            mens.setSender(self.myAgent.getAID())
            aid=AID.aid(m,["xmpp://"+m])
            mens.addReceiver(aid)
            mens.setOntology("Restaurant")
            mens.setContent(about)
            print "Solicitamos"+str(mens)
            self.sendPrivateMessage(i,m)
        time.sleep(100)
        mens=self.receiveMessage()
        while mens:
            print "Recibimos"
            mens
            mens=self.receiveMessage()




if __name__ == "__main__":
    agent = "siteb@apolo.dsic.upv.es"
    #agent = "agent@thx1138.dsic.upv.es"
    #agent = "agent@tatooine.dsic.upv.es"
    b = Example(agent,"pasword")
    b.start()








